<?php

namespace App\Http\Controllers\Admin\Wechat\Fun;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;

use App\Models\Wechat\Customer;
use App\Models\Config;
use App\Models\Wechat\Reply;
use Validator;

class CustomerController extends AdminController
{
	/**
     * 获取列表数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    function getLists(Request $request ){
    	$pageIndex = (int)$request->input('page') ?  $request->input('page') : 1;
        $length    = (int)$request->input('length') ?  $request->input('length') : 10;
        $start     = ($pageIndex-1)*$length;

    	$where = [];
        $subscribe = $request->input('subscribe');
        if($subscribe>-1){
            $where ['subscribe'] = $subscribe;
        }
        $customerModel = Customer::where($where);

    	$data['total'] = $customerModel->count();
    	if($data['total']>0){
    		$data['result'] = $customerModel->orderBy('updated_at','desc')->skip($start)->take($length)->get()->toArray();
    	}
    	$this->ajaxJson(0,'',$data);
    } 

    /**
     * 获取客服开启状态
     * @return [type] [description]
     */
    function getSwitch(){
        $reply = new Reply();
        $key = $reply->staticName['customer_switch'];
        $config = new Config();
        $customerSwitch = $config->cacheFindByKey($key);
        $bool = false;
        if($customerSwitch && $customerSwitch->switch){
            $bool = true;
        }
        $this->ajaxJson(0,'',['bool'=>$bool]);
    }

	/**
	 * 更新客服
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
	function postUpdate(Request $request){

		$data  = $request->all();
		$validator = $this->formValidator($data);
        if($validator->fails()){
            $this->ajaxJson(1,$validator->errors()->first());
        }
        $suffix = '@'.config('wechat.official_account.default.wechat_number');
        $error = config('wechaterrorcode');
        $customer_service = app('wechat.official_account')->customer_service;
        //保存客服信息
        try {
        	if($data['id']){
        		$result = $customer_service->update($data['account'].$suffix,$data['nickname']);
	        }else{
	        	$result = $customer_service->create($data['account'].$suffix,$data['nickname']);
	        }
        } catch (\Exception $e) {
        	$code = $e->formattedResponse['errcode'];
        	$this->ajaxJson(1,'更新客服异常:'.(array_key_exists($code,$error)==true ? $error[$code] : $e->formattedResponse['errmsg']));
        }
        if($result['errcode']){
        	$code = $result['errcode'];
        	$this->ajaxJson(1,'更新客服异常:'.(array_key_exists($code,$error)==true ? $error[$code] : $result['errmsg']));
        }
        //设置客服头像
        try {
        	$result = $customer_service->setAvatar($data['account'].$suffix, base_path().'/public'.$data['headimgurl']);
        } catch (\Exception $e) {
        	$code = $e->formattedResponse['errcode'];
        	$this->ajaxJson(1,'设置客服头像异常:'.(array_key_exists($code,$error)==true ? $error[$code] : $e->formattedResponse['errmsg']));
        }
        if($result['errcode']){
        	$code = $result['errcode'];
        	$this->ajaxJson(1,'设置客服头像异常:'.(array_key_exists($code,$error)==true ? $error[$code] : $result['errmsg']));
        }
        //数据入库
        if($data['id']){
        	$customer = $this->_get_one($data['id']);
        }else{
        	$customer = new Customer();
        }
        $customer->account = $data['account'].$suffix;
        $customer->nickname = $data['nickname'];
        $customer->headimgurl = $data['headimgurl'];
        $customer->save();
        $this->ajaxJson(0,'更新成功');
	}

    /**
     * 邀请微信用户绑定
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    function postInvite(Request $request){
        $wechatNo = $request->input('wechatNo');
        $customer = $this->_get_one($request->input('id'));
        $account  = $customer->account;
        $error    = config('wechaterrorcode');
        try {
            $result = app('wechat.official_account')->customer_service->invite($account,$wechatNo);
        } catch (\Exception $e) {
            $code = $e->formattedResponse['errcode'];
            $this->ajaxJson(1,'邀请异常:'.(array_key_exists($code,$error)==true ? $error[$code] : $e->formattedResponse['errmsg']));
        }
        if($result['errcode']){
            $code = $result['errcode'];
            $this->ajaxJson(1,'邀请异常:'.(array_key_exists($code,$error)==true ? $error[$code] : $result['errmsg']));
        }
        $customer->inviteWechatNo = $wechatNo;
        $customer->inviteExpireTime = date('Y-m-d H:i:s',strtotime('+1 days'));
        $customer->inviteStatus = 1;
        $customer->save();
        $this->ajaxJson(0,'邀请成功,请等待确认');
    }

    /**
     * 微信客服同步
     * @return [type] [description]
     */
    function postSync(){
        $error    = config('wechaterrorcode');
        try {
            $result = app('wechat.official_account')->customer_service->list();
        } catch (\Exception $e) {
            $code = $e->formattedResponse['errcode'];
            $this->ajaxJson(1,'刷新异常:'.(array_key_exists($code,$error)==true ? $error[$code] : $e->formattedResponse['errmsg']));
        }
        if(isset($result['errcode'])){
            $code = $result['errcode'];
            $this->ajaxJson(1,'刷新异常:'.(array_key_exists($code,$error)==true ? $error[$code] : $result['errmsg']));
        }
        $list = $result['kf_list'];
        foreach ($list as $cu) {
            $customer = Customer::where('account',$cu['kf_account'])->first();
            //不存在的客服,才更新昵称、账号、头像
            if(!$customer){
                $customer = new Customer();
                $customer->account = $cu['kf_account'];
                $customer->nickname = $cu['kf_nick'];
                $customer->headimgurl = $cu['kf_headimgurl'];
            }
            $customer->wechatNo = isset($cu['kf_wx']) ? $cu['kf_wx'] : '';
            $customer->inviteWechatNo = isset($cu['invite_wx']) ? $cu['invite_wx'] : '';
            $customer->inviteExpireTime = isset($cu['invite_expire_time']) ? date('Y-m-d H:i:s',$cu['invite_expire_time']) : null;
            $inviteStatusArr = ['waiting'=>1,'rejected'=>2,'expired'=>3];
            $customer->inviteStatus = isset($cu['invite_status']) ? $inviteStatusArr[$cu['invite_status']] : 0;
            $customer->save();
        }
        $this->ajaxJson(0,'刷新成功');
    }

    /**
     * 客服开关
     * @return [type] [description]
     */
    function postSwitch(Request $request){
        $reply = new Reply();
        $switch = $request->input('switch');
        $key = $reply->staticName['customer_switch'];
        $config = new Config();
        $customerSwitch = $config->cacheFindByKey($key);
        if(!$customerSwitch){
            $customerSwitch = new Config();
        }
        $customerSwitch->key = $key;
        $customerSwitch->switch = $switch=='true' ? 1 : 0 ;
        $customerSwitch->save();
        $config->cacheEmpty($key);
        $this->ajaxJson(0,'操作成功');
    }

	/**
	 * 获取单个
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	function getOne($id){
		$customer = $this->_get_one($id);
		$this->ajaxJson(0,'',$customer);
	}

	/**
	 * 删除单个
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	function deleteCustomer($id){
		$customer = $this->_get_one($id);
		try {
			$result =app('wechat.official_account')->customer_service->delete($customer->account);
            $customer->delete();
            $this->ajaxJson(0,'');
		} catch (Exception $e) {
            $this->ajaxJson(1,'删除客服异常');
		}
	}

	/**
	 * 验证账号唯一
	 * @return [type] [description]
	 */
	function checkUniqueAccount(Request $request){
		$this->ajaxJson(0,'',['bool'=>$this->_check_account($request->input('account'),$request->input('id'))]);
	}

	/**
	 * 验证账号唯一
	 * @param  [type] $account [description]
	 * @return [type]          [description]
	 */
	function _check_account($account,$id){
		$customer = Customer::where('id','!=',$id)->where('account',$account)->first();
		if($customer){
			return true;
		}
		return false;
	}

	function _get_one($id){
		$customer = Customer::find($id);
		if(!$customer){
			$this->ajaxJson(1,'不存在的客服数据');
		}
		return $customer;
	}

	/**
     * 数据验证
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    private function formValidator(array $data){
        $attribute =  array(
			'id'       => '客服数据',
			'account'  => '客服帐号',
			'nickname' => '客服昵称',
        );

        $message  = array(
            'required'    => ':attribute必须填写',
            'numeric' => ':attribute必须是数字',
            'exists' => ':attribute不存在'
        );

        return Validator::make($data, [
        	'id' => 'required|numeric',
			'account'  => 'bail|required',
			'nickname' => 'bail|required',
        ],$message,$attribute);
    }
}
